import com.mysql.jdbc.Connection;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import utils.DBUtils;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message/add2")
public class AddMessageServletV2 extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       int result=-1;
        //1.得到参数并校验
        String from=req.getParameter("from");
        String to=req.getParameter("to");
        String msg=req.getParameter("msg");
        if(StringUtils.hasLength(from) && StringUtils.hasLength(to) && StringUtils.hasLength(msg)){
            //2.将表白对象加入到数据库
            //2.1 得到connection
            Connection connection=DBUtils.getConnection();
            //2.2 拼装sql 创建执行器
            String sql="insert into messages(`from`,`to`,`message`) values(?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,from);
            statement.setString(2,to);
            statement.setString(3,msg);
            //2.3 执行执行器,并返回结果
            result = statement.executeUpdate();
            //2.4 关闭资源
            DBUtils.close(null,statement,connection);
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println(result);
    }
}

